import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    list: [],
    inputValue: '', // 用户输入的最新值
    maxId: 0,
    btnStatus: 'all'
  },
  mutations: {
    // 切换完成与否的状态
    changeBtnStatus(state, status) {
      state.btnStatus = status
    },

    // 初始化 list 数据列表
    initList(state, list) {
      state.list = list
    },

    // 同步用户输入的最新值
    setInputValue(state, value) {
      state.inputValue = value
    },

    // 添加新事项
    addItem(state) {
      // 添加新事项对象
      const newTodo = {
        id: state.maxId,
        info: state.inputValue,
        done: false
      }

      state.list.push(newTodo)
      state.inputValue = ''
      state.maxId++
    },

    // 移除事项
    removeItem(state, id) {
      // 如果值判断不等于，返回的是 -1
      // 否则返回对应的索引
      const index = state.list.findIndex(item => item.id === id)

      if (index !== -1) {
        state.list.splice(index, 1)
      }
    },

    // 更改状态
    changeStatus(state, params) {
      const index = state.list.findIndex(item => item.id === params.id)

      if (index !== -1) {
        state.list[index].done = params.done
      }
    },

    // 清空已完成
    clearFinish(state) {
      state.list = state.list.filter(item => item.done === false)
    }
  },
  actions: {
    getList(context) {
      axios.get('/list.json').then(data => {
        context.commit('initList', data.data)
      })
    }
  },
  getters: {
    // 计算总条数
    finishAll(state) {
      // return state.list.filter(item => item.done === false).length
      const newArr = state.list.filter(item => item.done === false)
      return newArr.length
    },

    // 切换状态后的数据
    changeData(state) {
      // if (state.btnStatus === 'all') {
      //   return state.list
      // }

      // if (state.btnStatus === 'undone') {
      //   return state.list.filter(item => item.done === false)
      // }

      // if (state.btnStatus === 'done') {
      //   return state.list.filter(item => item.done === true)
      // }

      // return state.list

      switch (state.btnStatus) {
        case 'all':
          return state.list
        case 'undone':
          return state.list.filter(item => item.done === false)
        case 'done':
          return state.list.filter(item => item.done === true)
        default:
          return state.list
      }
    }
  }
})
